
import CoreImage

struct Utils {
    
    // MARK: - 手机号验证
    static func isMobile(mobile:String?) -> Bool {
        if let trueMobile = mobile {
//            let mobileReg = "^1\\d{10}$"
            let mobileReg = "^1+[3456789]+\\d{9}"
            let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobileReg)
            return regextestmobile.evaluate(with: trueMobile)
        }
        return false
    }
    
    // MARK: - 手机号隐藏中间
    static func hideMiddleDigitsInPhoneNumber(_ phoneNumber: String) -> String {
        guard phoneNumber.count == 11 else { return phoneNumber }
        var formattedPhoneNumber = phoneNumber
        if formattedPhoneNumber.count >= 7 {
            let startIndex = formattedPhoneNumber.index(formattedPhoneNumber.startIndex, offsetBy: 3)
            let endIndex = formattedPhoneNumber.index(formattedPhoneNumber.startIndex, offsetBy: 6)
            let range = startIndex...endIndex
            formattedPhoneNumber.replaceSubrange(range, with: "****")
        }
        return formattedPhoneNumber
    }
    
    // MARK: - 昵称隐藏末尾
    static func hideTailDigitsInNickName(_ nickname: String) -> String {
        guard nickname.count > 0 else { return nickname }
        return "\(nickname.prefix(1))" + "**"
    }
    
    // MARK: - 验证邮箱
    static func validateEmail(email:String?) -> Bool {
        if let trueEmail = email {
            let emailRegex: String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
            let emailTest: NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
            return emailTest.evaluate(with: trueEmail)
        }
        return false
    }
    
    // MARK: - textField 长度裁剪
    static func clipTextFieldTextLength(textField: UITextField, limitNum: Int) -> String? {
        
        var finalText = textField.text
        if let text = textField.text, limitNum > 0 && text.count > limitNum {
            
            if let language = UITextInputMode.activeInputModes.first?.primaryLanguage, language == "zh-Hans", let range = textField.markedTextRange {
                
                
                let start = range.start
                let end = range.end
                
                let selLength = textField.offset(from: start, to: end)
                let contentLength = text.count - selLength

                if (contentLength > limitNum) {
                    finalText = text.substring(start: 0, limitNum)
                }
            } else {
                finalText = text.substring(start: 0, limitNum)
            }
            
        }
        return finalText
    }
    static func clipTextViewTextLength(textView: UITextView, limitNum: Int) -> String? {
        
        var finalText = textView.text
        if let text = textView.text, limitNum > 0 && text.count > limitNum {
            
            if let language = UITextInputMode.activeInputModes.first?.primaryLanguage, language == "zh-Hans", let range = textView.markedTextRange {
                
                let start = range.start
                let end = range.end
                
                let selLength = textView.offset(from: start, to: end)
                let contentLength = text.count - selLength

                if (contentLength > limitNum) {
                    finalText = text.substring(start: 0, limitNum)
                }
            } else {
                finalText = text.substring(start: 0, limitNum)
            }
            
        }
        return finalText
    }
    
}
// MARK: ----- 字符串 map array 互转
extension Utils {
    
    // 字 -> arr
    static func getArrayFromJSONString(jsonString:String) -> NSArray {
        
        if jsonString.count == 0 {
            return NSArray()
        }
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if array != nil {
            return array as! NSArray
        }
        return array as! NSArray
        
    }
    // 字 -> map
    static func getDictionaryFromJSONString(jsonString:String) -> NSDictionary {
        
        if jsonString.count == 0 {
            return NSDictionary()
        }
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
        
    }
    // map -> 字
    static func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            MYLog("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
    // array -> 字
    static func getJSONStringFromArray(array:NSArray) -> String {
        
        if (!JSONSerialization.isValidJSONObject(array)) {
            MYLog("无法解析出JSONString")
            return ""
        }
        
        let data : NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
}

// MARK: - 获取控制器
extension Utils {
    
    /// 获取顶层控制器 根据window
    static func getTopVC() -> UIViewController? {
        var window = UIApplication.shared.keyWindow
        //是否为当前显示的window
        if window?.windowLevel != UIWindow.Level.normal{
          let windows = UIApplication.shared.windows
          for  windowTemp in windows{
            if windowTemp.windowLevel == UIWindow.Level.normal{
              window = windowTemp
              break
          }
        }
      }
      let vc = window?.rootViewController
      return getTopVC(withCurrentVC: vc)
     }
    
    ///根据控制器获取 顶层控制器
    static func getTopVC(withCurrentVC VC :UIViewController?) -> UIViewController? {
        if VC == nil {
            return nil
        }
    if let presentVC = VC?.presentedViewController {
        //modal出来的 控制器
        return getTopVC(withCurrentVC: presentVC)
    }else if let tabVC = VC as? UITabBarController {
        // tabBar 的跟控制器
        if let selectVC = tabVC.selectedViewController {
          return getTopVC(withCurrentVC: selectVC)
        }
        return nil
    } else if let naiVC = VC as? UINavigationController {
        // 控制器是 nav
        return getTopVC(withCurrentVC:naiVC.getVisibleViewController)
      } else {
        // 返回顶控制器
        return VC
        }
    }
    
    static func showMessage(message: String) {
        
        guard let topVC = getTopVC() else { return }
        topVC.showMessage(message: message)
        
    }
    static func showMessage(message: String, afterDelay: TimeInterval = CGFloat.app_hubInterval) {

        guard let topVC = getTopVC() else { return }
        topVC.showMessage(message: message, afterDelay: afterDelay)

    }
    
    static func layerCornerRadius(_ view: UIView, _ roundFrame: CGRect,_ radius: CGFloat,_ corners: UIRectCorner = [.allCorners]) {
        let path = UIBezierPath(roundedRect: roundFrame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = roundFrame
        maskLayer.path = path.cgPath
        view.layer.mask = maskLayer
    }
    
}

struct Device {
    
    static let isPad = UIDevice.current.userInterfaceIdiom == .pad
    
    /// 获取app的全部信息
    static func getAppInfomation() -> Dictionary<String, Any> {
        return Bundle.main.infoDictionary!
    }
    /// 获取app昵称
    static func getAppName() -> String {
        
        // 获取app信息
        let infoDictionary: Dictionary = Bundle.main.infoDictionary!
        // 程序名称
        let appDisplayName: String = infoDictionary["CFBundleDisplayName"] as! String
        
        return appDisplayName
    }
    /// 获取bundle id
    static func getBundleIdentifier() -> String {
        
        // 获取app信息
        let infoDictionary: Dictionary = Bundle.main.infoDictionary!
        // bundle id
        let appDisplayName: String = infoDictionary["CFBundleIdentifier"] as! String
        
        return appDisplayName
    }
    /// 获取app版本号
    static func getAppVersion() -> String {
        
        //获取app信息
        let infoDictionary: Dictionary = Bundle.main.infoDictionary!
        //程序版本
        let appVersion: String = infoDictionary ["CFBundleShortVersionString"] as! String
        
        return appVersion
    }
    /// 获取app版本号
    static func getAppBuild() -> String {
        
        //获取app信息
        let infoDictionary: Dictionary = Bundle.main.infoDictionary!
        //程序版本
        let appVersion: String = infoDictionary ["CFBundleVersion"] as! String
        
        return appVersion
    }
    /// 获取设备名称
    static func getDeviceName () -> String {
        return UIDevice.current.name
    }
    /// 获取系统名称
    static func getSystemName () -> String {
        return UIDevice.current.systemName
    }
    /// 获取系统版本号
    static func getIosVersion() -> String {
        let iosVersion : NSString = UIDevice.current.systemVersion as NSString
        return iosVersion as String
    }
    /// 获取设备型号
    static func getSystemModel() -> String {
        //设备型号
        let model = UIDevice.current.model
        //设备区域化型号如A1533
        // let localizedModel = UIDevice.current.localizedModel
        return model
    }
    
    /// 获取设备区域化型号如A1533
    static func getLocalizedModel() -> String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        return ""
    }
    
    /// 获取当前设备IP
    static func getOperatorsIP() -> String? {
        var addresses = [String]()
        var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
        if getifaddrs(&ifaddr) == 0 {
            var ptr = ifaddr
            while (ptr != nil) {
                let flags = Int32(ptr!.pointee.ifa_flags)
                var addr = ptr!.pointee.ifa_addr.pointee
                if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                    if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
                        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                        if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String(validatingUTF8:hostname) {
                                addresses.append(address)
                            }
                        }
                    }
                }
                ptr = ptr!.pointee.ifa_next
            }
            freeifaddrs(ifaddr)
        }
        return addresses.first
    }
    
    static func isPortrait() -> Bool {
        let size = CGSize(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
        return size.height > size.width
    }
}





